package com.zxl.manager.controller;

import com.google.gson.Gson;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by jimmy on 2017/7/13.
 */
@Controller
public class FileController {

    private Gson gson = new Gson();

    @RequestMapping("/fileUpload")
    @ResponseBody
    public String fileUpload(@RequestParam MultipartFile[] file , HttpSession httpSession){
        Map<String,Object> resMap = new HashMap<>();
        List<String> filenames = new ArrayList<>();
         try {
             for (MultipartFile mfile : file) {
                 if (mfile.getSize() > 0) {
                     String fileName = mfile.getOriginalFilename();
                     if (fileName.endsWith("jpg") || fileName.endsWith("png") || fileName.endsWith("gif")) {
                         String leftPath = httpSession.getServletContext().getRealPath("/image");
                         File dir = new File(leftPath);
                         if (!dir.exists()) {
                             dir.mkdir();
                         }
                         System.out.println(leftPath);
                         File filea = new File(leftPath, fileName);
                         mfile.transferTo(filea);
                         filenames.add(fileName);
                     }
                 }
             }
        }catch (Exception e){
            e.printStackTrace();
        }
        resMap.put("code","0");
        resMap.put("filenames",filenames);
        resMap.put("msg","ok");
        return gson.toJson(resMap);
    }
}
